<template>
  <div class="leave-application">
    <div class="header">
      <h2>请假申请</h2>
      <el-button type="primary" @click="handleApply" :icon="Plus">
        申请请假
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="请假类型">
          <el-select
            v-model="searchForm.leaveType"
            placeholder="请选择请假类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="type in leaveTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 请假申请列表 -->
    <el-card>
      <el-table
        :data="leaveList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="applicantName" label="申请人" width="120" align="center" />
        <el-table-column prop="leaveTypeName" label="请假类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getLeaveTypeTagType(row.leaveType)">
              {{ row.leaveTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="请假时长" width="100" align="center">
          <template #default="{ row }">
            {{ row.duration }} 天
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="请假事由" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="approverName" label="审批人" width="120" align="center" />
        <el-table-column prop="approveTime" label="审批时间" width="180" align="center">
          <template #default="{ row }">
            {{ row.approveTime ? formatDateTime(row.approveTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="success"
              link
              @click="handleApprove(row)"
              :disabled="!canApprove(row)"
            >
              审批
            </el-button>
            <el-button
              size="small"
              type="danger"
              link
              @click="handleCancel(row)"
              :disabled="!canCancel(row)"
            >
              撤销
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 申请/编辑请假对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="leaveFormRef"
        :model="leaveForm"
        :rules="leaveRules"
        label-width="100px"
      >
        <el-form-item label="请假类型" prop="leaveType">
          <el-select
            v-model="leaveForm.leaveType"
            placeholder="请选择请假类型"
            style="width: 100%"
          >
            <el-option
              v-for="type in leaveTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="请假时间" prop="timeRange">
          <el-date-picker
            v-model="leaveForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            @change="handleTimeRangeChange"
          />
        </el-form-item>

        <el-form-item label="请假时长" prop="duration">
          <el-input
            v-model="leaveForm.duration"
            placeholder="自动计算"
            readonly
            style="width: 100%"
          >
            <template #append>天</template>
          </el-input>
        </el-form-item>

        <el-form-item label="请假事由" prop="reason">
          <el-input
            v-model="leaveForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入请假事由"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="证明材料">
          <el-upload
            v-model:file-list="leaveForm.attachments"
            action="#"
            multiple
            :auto-upload="false"
            :on-remove="handleFileRemove"
            :on-change="handleFileChange"
            :before-upload="beforeFileUpload"
            list-type="text"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片、文档等文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ leaveForm.id ? '更新' : '提交' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看请假详情对话框 -->
    <el-dialog
      title="请假详情"
      v-model="detailDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请人">
          {{ currentLeave.applicantName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="请假类型">
          <el-tag :type="getLeaveTypeTagType(currentLeave.leaveType)">
            {{ getLeaveTypeLabel(currentLeave.leaveType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请假时长">
          {{ currentLeave.duration }} 天
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ formatDateTime(currentLeave.startTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="结束时间">
          {{ formatDateTime(currentLeave.endTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="申请状态" :span="2">
          <el-tag :type="getStatusTagType(currentLeave.status)">
            {{ getStatusLabel(currentLeave.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请假事由" :span="2">
          {{ currentLeave.reason || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="审批人">
          {{ currentLeave.approverName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="审批时间">
          {{ currentLeave.approveTime ? formatDateTime(currentLeave.approveTime) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="审批意见" :span="2">
          {{ currentLeave.approveRemark || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">
          {{ formatDateTime(currentLeave.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDateTime(currentLeave.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      title="请假审批"
      v-model="approveDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      class="approve-dialog"
    >
      <el-form
        ref="approveFormRef"
        :model="approveForm"
        :rules="approveRules"
        label-width="80px"
      >
        <el-form-item label="申请人">
          <el-input
            v-model="currentLeave.applicantName"
            readonly
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="请假类型">
          <el-input
            :value="getLeaveTypeLabel(currentLeave.leaveType)"
            readonly
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="请假时间">
          <el-input
            :value="`${formatDateTime(currentLeave.startTime)} 至 ${formatDateTime(currentLeave.endTime)}`"
            readonly
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="请假时长">
          <el-input
            :value="`${currentLeave.duration} 天`"
            readonly
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="请假事由">
          <el-input
            v-model="currentLeave.reason"
            type="textarea"
            :rows="3"
            readonly
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="审批意见" prop="approveRemark">
          <el-input
            v-model="approveForm.approveRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入审批意见"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button 
            type="danger" 
            @click="handleReject" 
            :loading="approving"
            :disabled="!approveForm.approveRemark"
          >
            不通过
          </el-button>
          <el-button 
            type="primary" 
            @click="handleApprovePass" 
            :loading="approving"
          >
            通过
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { leaveApi } from '@/api/leave'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const submitting = ref(false)
const approving = ref(false)
const leaveFormRef = ref()
const approveFormRef = ref()
const leaveList = ref([])
const leaveTypes = ref([])

// 搜索表单
const searchForm = reactive({
  leaveType: '',
  status: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 请假表单
const leaveForm = reactive({
  id: null,
  leaveType: '',
  timeRange: [],
  startTime: '',
  endTime: '',
  duration: 0,
  reason: '',
  attachments: []
})

// 审批表单
const approveForm = reactive({
  approveRemark: ''
})

// 当前查看的请假记录
const currentLeave = reactive({})

// 状态选项
const statusOptions = [
  { value: 0, label: '待审批' },
  { value: 1, label: '已通过' },
  { value: 2, label: '已拒绝' },
  { value: 3, label: '已撤销' }
]

// 表单验证规则
const leaveRules = {
  leaveType: [
    { required: true, message: '请选择请假类型', trigger: 'change' }
  ],
  timeRange: [
    { required: true, message: '请选择请假时间', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入请假事由', trigger: 'blur' },
    { min: 5, max: 500, message: '请假事由长度在 5 到 500 个字符', trigger: 'blur' }
  ]
}

// 审批表单验证规则
const approveRules = {
  approveRemark: [
    { required: true, message: '请输入审批意见', trigger: 'blur' },
    { min: 2, max: 200, message: '审批意见长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return leaveForm.id ? '编辑请假申请' : '申请请假'
})

// 方法
// 加载请假列表
const loadLeaveList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    
    // 处理时间范围参数
    if (params.dateRange && params.dateRange.length === 2) {
      params.startDate = params.dateRange[0]
      params.endDate = params.dateRange[1]
      delete params.dateRange
    }
    
    const response = await leaveApi.getLeaveList(params)
    if (response && response.code === 1) {
      leaveList.value = response.data?.rows || response.data || []
      pagination.total = response.data?.total || 0
    } else {
      ElMessage.error(response?.msg || '获取请假列表失败')
    }
  } catch (error) {
    ElMessage.error('获取请假列表失败')
    console.error('Error loading leave list:', error)
  } finally {
    loading.value = false
  }
}

// 加载请假类型
const loadLeaveTypes = async () => {
  try {
    const response = await leaveApi.getLeaveTypes()
    if (response && response.code === 1) {
      leaveTypes.value = response.data || []
    } else {
      // 默认类型
      leaveTypes.value = [
        { value: 1, label: '年假' },
        { value: 2, label: '病假' },
        { value: 3, label: '事假' },
        { value: 4, label: '婚假' },
        { value: 5, label: '产假' },
        { value: 6, label: '丧假' },
        { value: 7, label: '调休' }
      ]
    }
  } catch (error) {
    console.error('Error loading leave types:', error)
    // 使用默认类型
    leaveTypes.value = [
      { value: 1, label: '年假' },
      { value: 2, label: '病假' },
      { value: 3, label: '事假' },
      { value: 4, label: '婚假' },
      { value: 5, label: '产假' },
      { value: 6, label: '丧假' },
      { value: 7, label: '调休' }
    ]
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadLeaveList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    leaveType: '',
    status: '',
    dateRange: []
  })
  pagination.page = 1
  loadLeaveList()
}

// 申请请假
const handleApply = () => {
  Object.assign(leaveForm, {
    id: null,
    leaveType: '',
    timeRange: [],
    startTime: '',
    endTime: '',
    duration: 0,
    reason: '',
    attachments: []
  })
  dialogVisible.value = true
  nextTick(() => {
    leaveFormRef.value?.clearValidate()
  })
}

// 查看详情
const handleView = (row) => {
  Object.assign(currentLeave, row)
  detailDialogVisible.value = true
}

// 审批请假
const handleApprove = (row) => {
  Object.assign(currentLeave, row)
  Object.assign(approveForm, {
    approveRemark: ''
  })
  approveDialogVisible.value = true
  nextTick(() => {
    approveFormRef.value?.clearValidate()
  })
}

// 撤销请假
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要撤销请假申请吗？`,
      '提示',
      {
        type: 'warning',
        confirmButtonText: '确定撤销',
        cancelButtonText: '取消'
      }
    )
    
    await leaveApi.cancelLeave(row.id)
    ElMessage.success('撤销成功')
    loadLeaveList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || error.message || '撤销失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await leaveFormRef.value.validate()
    if (!valid) return

    submitting.value = true
    
    // 确保时间格式正确
    const submitData = {
      ...leaveForm,
      startTime: leaveForm.timeRange ? leaveForm.timeRange[0] : '',
      endTime: leaveForm.timeRange ? leaveForm.timeRange[1] : ''
    }
    
    // 移除前端不需要的字段
    delete submitData.timeRange
    
    if (leaveForm.id) {
      await leaveApi.updateLeave(submitData)
      ElMessage.success('更新请假申请成功')
    } else {
      await leaveApi.addLeave(submitData)
      ElMessage.success('申请请假成功')
    }
    
    dialogVisible.value = false
    loadLeaveList()
  } catch (error) {
    console.error('提交错误:', error)
    ElMessage.error(error.response?.data?.message || error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 审批通过
const handleApprovePass = async () => {
  try {
    const valid = await approveFormRef.value.validate()
    if (!valid) return

    approving.value = true
    
    const approveData = {
      id: currentLeave.id,
      status: 1, // 已通过
      approveRemark: approveForm.approveRemark
    }
    
    await leaveApi.approveLeave(approveData)
    ElMessage.success('审批通过')
    approveDialogVisible.value = false
    loadLeaveList()
  } catch (error) {
    console.error('审批错误:', error)
    ElMessage.error(error.response?.data?.message || error.message || '审批失败')
  } finally {
    approving.value = false
  }
}

// 审批不通过
const handleReject = async () => {
  try {
    const valid = await approveFormRef.value.validate()
    if (!valid) return

    approving.value = true
    
    const approveData = {
      id: currentLeave.id,
      status: 2, // 已拒绝
      approveRemark: approveForm.approveRemark
    }
    
    await leaveApi.approveLeave(approveData)
    ElMessage.success('审批不通过')
    approveDialogVisible.value = false
    loadLeaveList()
  } catch (error) {
    console.error('审批错误:', error)
    ElMessage.error(error.response?.data?.message || error.message || '审批失败')
  } finally {
    approving.value = false
  }
}

// 时间范围变化
const handleTimeRangeChange = (value) => {
  if (value && value.length === 2) {
    const start = new Date(value[0])
    const end = new Date(value[1])
    const duration = (end - start) / (1000 * 60 * 60 * 24) // 计算天数
    leaveForm.duration = Math.round(duration * 100) / 100 // 保留两位小数
  } else {
    leaveForm.duration = 0
  }
}

// 文件上传相关方法
const handleFileRemove = (file, fileList) => {
  leaveForm.attachments = fileList
}

const handleFileChange = (file, fileList) => {
  leaveForm.attachments = fileList
}

const beforeFileUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return false // 手动上传
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadLeaveList()
}

// 页码改变
const handleCurrentChange = (page) => {
  pagination.page = page
  loadLeaveList()
}

// 工具方法
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-').replace(',', '')
}

const getLeaveTypeLabel = (type) => {
  const typeObj = leaveTypes.value.find(t => t.value === type)
  return typeObj ? typeObj.label : '未知'
}

const getLeaveTypeTagType = (type) => {
  const typeMap = {
    1: 'success', // 年假
    2: 'warning', // 病假
    3: 'danger',  // 事假
    4: 'primary', // 婚假
    5: 'info',    // 产假
    6: '',        // 丧假
    7: 'success'  // 调休
  }
  return typeMap[type] || 'info'
}

const getStatusLabel = (status) => {
  const statusObj = statusOptions.find(s => s.value === status)
  return statusObj ? statusObj.label : '未知'
}

const getStatusTagType = (status) => {
  const statusMap = {
    0: 'warning', // 待审批
    1: 'success', // 已通过
    2: 'danger',  // 已拒绝
    3: 'info'     // 已撤销
  }
  return statusMap[status] || 'info'
}

// 权限控制方法
const canApprove = (row) => {
  return row.status === 0 // 只有待审批状态可审批
}

const canCancel = (row) => {
  return row.status === 0 // 只有待审批状态可撤销
}

// 生命周期
onMounted(() => {
  loadLeaveList()
  loadLeaveTypes()
})
</script>

<style scoped>
.leave-application {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-descriptions) {
  margin-top: 10px;
}

:deep(.el-upload-list) {
  margin-top: 10px;
}

/* 审批对话框按钮样式 */
:deep(.approve-dialog .el-dialog__footer) {
  display: flex;
  justify-content: space-between;
}
</style>